#!/bin/bash

# On crée un fichier temporaire sur disque
# Il n'est pas possible de fonctionner avec des pipes uniquement car ça crée des deadlocks
# La commande de la console doit être passée dans la variable MYSQL_CMD

if [ "$MYSQL_CMD" == "" ]
then
    echo "Missing MYSQL_CMD env var"
    exit 1
fi

GENERATOR_SCRIPT=$(dirname "$0")"/_migration_sql_collation.sql"
TMP_FILE=/tmp/caerp-migrate-utf8mb4.sql
echo "-> Generating ALTER commands in a ${TMP_FILE}"
echo "SET FOREIGN_KEY_CHECKS=0;" > $TMP_FILE
cat $GENERATOR_SCRIPT | bash -c "$MYSQL_CMD" | grep "CHARACTER" | grep "ALTER" >> $TMP_FILE
echo "SET FOREIGN_KEY_CHECKS=1;" >> $TMP_FILE
echo " * File generated"

echo "-> Launching the commands toward the database"
cat $TMP_FILE | bash -c "$MYSQL_CMD"
echo " * Done"
